﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

using AtletIS.Shared.AtletisService;
using AtletIS.Shared.Data.aDbDataSetTableAdapters;
using AtletIS.Shared.Helpers;
using System.ServiceModel;
using System.Threading;

namespace AtletIS.Shared.Forms
{
    public partial class frmSync : Form
    {
        #region Variables

        private SyncParameters syncParams;
        private BackgroundWorker bw;
        private DateTime dtStart;

        private bool bUploadCompetitionData = false;
        private bool bUploadSettingsTables = false;
        private bool bUploadPreChipData = false;

        private bool bContinueSync = true;

        #endregion

        #region Form

        public frmSync()
        {
            InitializeComponent();
            this.Icon = Properties.Resources.AtletIS64;

            this.bw = new BackgroundWorker();
            this.bw.WorkerReportsProgress = true;
            this.bw.DoWork += new DoWorkEventHandler(backgroundWorker_DoWork);
            this.bw.ProgressChanged += new ProgressChangedEventHandler(backgroundWorker_ProgressChanged);
            this.bw.RunWorkerCompleted += new RunWorkerCompletedEventHandler(backgroundWorker_RunWorkerCompleted);
        }

        private void frmSync_Load(object sender, EventArgs e)
        {
            Globals.ActiveCompetition = CompetitionHelper.ConvertToEntity(DatabaseHelper.GetCompetitionsActive().Rows[0]); // new CompetitionsTableAdapter().GetActive().Rows[0]);
            this.txtActiveCompetition.Text = Globals.ActiveCompetition.Name;

            this.lblProgress.Text = string.Empty;
        }

        private void frmSync_FormClosing(object sender, FormClosingEventArgs e)
        {
            Application.Exit();
        }

        #endregion

        #region Buttons

        private void tsbUploadCompetitionData_Click(object sender, EventArgs e)
        {
            if (this.bw.IsBusy)
            {
                MessageBox.Show("Prebieha upload, čakajte prosím!", "Upload", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            }
            else
            {
                this.gbCompetition.Enabled = true;
                this.gbTables.Enabled = false;

                this.lblProgress.Text = "Uploadujem preteky ...";

                this.bUploadCompetitionData = true;
                this.bUploadSettingsTables = false;
                this.bUploadPreChipData = false;

                this.bContinueSync = true;

                // Upload in background
                this.bw.RunWorkerAsync();
            }
        }

        private void tsbUploadSettingsTables_Click(object sender, EventArgs e)
        {
            if (this.bw.IsBusy)
            {
                MessageBox.Show("Prebieha upload, čakajte prosím!", "Upload", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            }
            else
            {
                this.gbCompetition.Enabled = false;
                this.gbTables.Enabled = true;

                this.lblProgress.Text = "Uploadujem číselníky ...";
                
                this.bUploadCompetitionData = false;
                this.bUploadSettingsTables = true;
                this.bUploadPreChipData = false;
                
                this.bContinueSync = true;

                // Upload in background
                this.bw.RunWorkerAsync();
            }
        }

        private void tsbUploadPreChipData_Click(object sender, EventArgs e)
        {
            if (this.bw.IsBusy)
            {
                MessageBox.Show("Prebieha upload, čakajte prosím!", "Upload", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            }
            else
            {
                this.gbCompetition.Enabled = false;
                this.gbTables.Enabled = false;

                this.lblProgress.Text = "Uploadujem prechody pred štartom ...";
                
                this.bUploadCompetitionData = false;
                this.bUploadSettingsTables = false;
                this.bUploadPreChipData = true;

                this.bContinueSync = true;

                // Upload in background
                this.bw.RunWorkerAsync();
            }
        }

        private void tsbUploadFinish_Click(object sender, EventArgs e)
        {
            this.bContinueSync = false;
        }

        private void tsbWeb_Click(object sender, EventArgs e)
        {
            frmSyncWeb frm = new frmSyncWeb();
            frm.ShowDialog();
        }

        private void tsbClose_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        #endregion

        #region BackgroundWorker

        void backgroundWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            int progress = 0;
            this.dtStart = DateTime.Now;

            try
            {
                if (this.bUploadCompetitionData)
                {
                    #region 1 Competition

                    if (chkCompetition.Checked)
                    {
                        if (Globals.ActiveCompetition.WebId == 0)
                        {
                            MessageBox.Show("Preteky nemajú zadané WebId, synchronizácia nie je možná!", "Sync", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                            return;
                        }

                        this.syncParams = new SyncParameters();
                        this.syncParams.ActiveTable = AtletisService.Tables.CompetitionsById;
                        this.syncParams.ActiveTableSpecified = true;
                        this.syncParams.ID = Globals.ActiveCompetition.WebId;
                        this.syncParams.IDSpecified = true;

                        CompetitionsTableAdapter taCompetitions = new CompetitionsTableAdapter();
                        DataTable dt = DatabaseHelper.GetCompetitionsActive(); // taCompetitions.GetActive();
                        DataTable dtOutput = UploadHelper.Upload(dt, syncParams);

                        // Update local DB
                        foreach (DataRow dr in dt.Rows)
                        {
                            if (dr["WebId"] == DBNull.Value || Convert.ToInt32(dr["WebId"]) == 0)
                            {
                                string filter = "[WebId] = " + dr["ID"].ToString();
                                dr["WebId"] = dtOutput.Select(filter)[0]["ID"];
                                dr["Sync"] = true;
                                taCompetitions.Update(dr);
                            }
                        }

                        progress += 1;
                        this.bw.ReportProgress(progress);
                    }

                    #endregion

                    #region 2 DisciplineList

                    if (chkDisciplineList.Checked)
                    {
                        this.syncParams = new SyncParameters();
                        this.syncParams.ActiveTable = Tables.DisciplineListForCompetition;
                        this.syncParams.ActiveTableSpecified = true;
                        this.syncParams.ID = Globals.ActiveCompetition.WebId;
                        this.syncParams.IDSpecified = true;

                        DisciplineListTableAdapter taDisciplineList = new DisciplineListTableAdapter();
                        DataTable dt = DatabaseHelper.GetDisciplineListByCompetitionIdSync(Globals.ActiveCompetition.ID); 
                        DataTable dtOutput = UploadHelper.Upload(dt, syncParams);

                        // Update local DB
                        foreach (DataRow dr in dt.Rows)
                        {
                            if (dr["WebId"] == DBNull.Value || Convert.ToInt32(dr["WebId"]) == 0)
                            {
                                string filter = "[WebId] = " + dr["ID"].ToString();
                                dr["WebId"] = dtOutput.Select(filter)[0]["ID"];
                                // dr["Sync"] = true;
                                // taDisciplineList.Update(dr);

                                DatabaseHelper.SetSyncAndWebId("DisciplineList", Convert.ToInt32(dr["ID"]), Convert.ToInt32(dr["WebId"]));
                            }
                        }

                        progress += 1;
                        this.bw.ReportProgress(progress);
                    }

                    #endregion

                    #region 3 ExtTextsForDisciplineList

                    if (chkExtTextsForDisciplineList.Checked)
                    {
                        this.syncParams = new SyncParameters();
                        this.syncParams.ActiveTable = AtletisService.Tables.ExtTextsForDisciplineList;
                        this.syncParams.ActiveTableSpecified = true;

                        this.syncParams.ID = Globals.ActiveCompetition.WebId;
                        this.syncParams.IDSpecified = true;

                        ExtTextsTableAdapter taExtTexts = new ExtTextsTableAdapter();
                        DataTable dt = DatabaseHelper.GetExtTextsForDisciplineListByCompetitionIdSync(Globals.ActiveCompetition.ID);
                        if (dt != null && dt.Rows.Count > 0)
                        {
                            DataTable dtOutput = UploadHelper.Upload(dt, syncParams);

                            // Update local DB
                            foreach (DataRow dr in dt.Rows)
                            {
                                if (dr["WebId"] == DBNull.Value || Convert.ToInt32(dr["WebId"]) == 0)
                                {
                                    string filter = "[WebId] = " + dr["ID"].ToString();
                                    dr["WebId"] = dtOutput.Select(filter)[0]["ID"];
                                    // dr["Sync"] = true;
                                    // taExtTexts.Update(dr);

                                    DatabaseHelper.SetSyncAndWebId("ExtTexts", Convert.ToInt32(dr["ID"]), Convert.ToInt32(dr["WebId"]));
                                }
                            }
                        }

                        progress += 1;
                        this.bw.ReportProgress(progress);
                    }

                    #endregion

                    #region 4 CheckPoints

                    if (chkCheckPoints.Checked)
                    {
                        this.syncParams = new SyncParameters();
                        this.syncParams.ActiveTable = AtletisService.Tables.CheckPoints;
                        this.syncParams.ActiveTableSpecified = true;

                        foreach (DataRow drDisciplineList in DatabaseHelper.GetDisciplineListByCompetitionIdAll(Globals.ActiveCompetition.ID)) 
                        // new DisciplineListTableAdapter().GetByCompetitionId(Globals.ActiveCompetition.ID))
                        {
                            this.syncParams.ID = Convert.ToInt32(drDisciplineList["WebId"]);
                            this.syncParams.IDSpecified = true;

                            CheckPointsTableAdapter taCheckPoints = new CheckPointsTableAdapter();
                            DataTable dt = DatabaseHelper.GetCheckPointsByDisciplineListId(Convert.ToInt32(drDisciplineList["ID"])); 
                            // taCheckPoints.GetByDisciplineListId(Convert.ToInt32(drDisciplineList["ID"]));
                            if (dt != null && dt.Rows.Count > 0)
                            {
                                DataTable dtOutput = UploadHelper.Upload(dt, syncParams);

                                // Update local DB
                                foreach (DataRow dr in dt.Rows)
                                {
                                    if (dr["WebId"] == DBNull.Value || Convert.ToInt32(dr["WebId"]) == 0)
                                    {
                                        string filter = "[WebId] = " + dr["ID"].ToString();
                                        dr["WebId"] = dtOutput.Select(filter)[0]["ID"];
                                        dr["Sync"] = true;
                                        taCheckPoints.Update(dr);
                                    }
                                }
                            }
                        }

                        progress += 1;
                        this.bw.ReportProgress(progress);
                    }

                    #endregion

                    #region 5 Performances

                    if (chkPerformances.Checked)
                    {
                        this.syncParams = new SyncParameters();
                        this.syncParams.ActiveTable = AtletisService.Tables.Performances;
                        this.syncParams.ActiveTableSpecified = true;

                        this.syncParams.ID = Globals.ActiveCompetition.WebId;
                        this.syncParams.IDSpecified = true;

                        PerformancesTableAdapter taPerformances = new PerformancesTableAdapter();
                        DataTable dt = DatabaseHelper.GetPerformancesByDisciplineListIdSync(Globals.ActiveCompetition.ID);
                        DataTable dtOutput = UploadHelper.Upload(dt, syncParams);

                        // Update local DB
                        foreach (DataRow dr in dt.Rows)
                        {
                            if (dr["WebId"] == DBNull.Value || Convert.ToInt32(dr["WebId"]) == 0)
                            {
                                string filter = "[WebId] = " + dr["ID"].ToString();
                                dr["WebId"] = dtOutput.Select(filter)[0]["ID"];
                                // dr["Sync"] = true;
                                // taPerformances.Update(dr);

                                DatabaseHelper.SetSyncAndWebId("Performances", Convert.ToInt32(dr["ID"]), Convert.ToInt32(dr["WebId"]));
                            }
                        }

                        progress += 1;
                        this.bw.ReportProgress(progress);
                    }

                    #endregion

                    #region 6 ExtTextsForPerformance

                    if (chkExtTextsForPerformance.Checked)
                    {
                        this.syncParams = new SyncParameters();
                        this.syncParams.ActiveTable = AtletisService.Tables.ExtTextsForPerformance;
                        this.syncParams.ActiveTableSpecified = true;

                        this.syncParams.ID = Globals.ActiveCompetition.WebId;
                        this.syncParams.IDSpecified = true;

                        ExtTextsTableAdapter taExtTexts = new ExtTextsTableAdapter();
                        DataTable dt = DatabaseHelper.GetExtTextsForPerformancesByCompetitionIdSync(Globals.ActiveCompetition.ID);
                        if (dt != null && dt.Rows.Count > 0)
                        {
                            DataTable dtOutput = UploadHelper.Upload(dt, syncParams);

                            // Update local DB
                            foreach (DataRow dr in dt.Rows)
                            {
                                if (dr["WebId"] == DBNull.Value || Convert.ToInt32(dr["WebId"]) == 0)
                                {
                                    string filter = "[WebId] = " + dr["ID"].ToString();
                                    dr["WebId"] = dtOutput.Select(filter)[0]["ID"];
                                    // dr["Sync"] = true;
                                    // taExtTexts.Update(dr);

                                    DatabaseHelper.SetSyncAndWebId("ExtTexts", Convert.ToInt32(dr["ID"]), Convert.ToInt32(dr["WebId"]));
                                }
                            }
                        }

                        progress += 1;
                        this.bw.ReportProgress(progress);
                    }

                    #endregion

                    #region 7 ChipData

                    if (chkChipData.Checked)
                    {
                        DataTable dt = DatabaseHelper.GetChipDataByCompetitionId(Globals.ActiveCompetition.ID); 
                        
                        if (dt != null && dt.Rows.Count > 0)
                        {
                            int count = UploadHelper.UploadChipData(dt);
                        }

                        progress += 1;
                        this.bw.ReportProgress(progress);
                    }

                    #endregion
                }

                if (this.bUploadSettingsTables)
                {
                    #region Categories

                    if (chkCategories.Checked)
                    {
                        this.syncParams = new SyncParameters();
                        this.syncParams.ActiveTable = AtletisService.Tables.Categories;
                        this.syncParams.ActiveTableSpecified = true;

                        CategoriesTableAdapter taCategories = new CategoriesTableAdapter();
                        DataTable dt = taCategories.GetData();
                        DataTable dtOutput = UploadHelper.Upload(dt, syncParams);

                        // Update local DB
                        foreach (DataRow dr in dt.Rows)
                        {
                            string filter = "[WebId] = " + dr["ID"].ToString();
                            dr["WebId"] = dtOutput.Select(filter)[0]["ID"];
                            // dr["Sync"] = true;
                            // taCategories.Update(dr);

                            DatabaseHelper.SetSyncAndWebId("Categories", Convert.ToInt32(dr["ID"]), Convert.ToInt32(dr["WebId"]));
                        }

                        progress += 1;
                        this.bw.ReportProgress(progress);
                    }

                    #endregion

                    #region Disciplines

                    if (chkDisciplines.Checked)
                    {
                        this.syncParams = new SyncParameters();
                        this.syncParams.ActiveTable = AtletisService.Tables.DisciplinesGroups;
                        this.syncParams.ActiveTableSpecified = true;

                        DisciplinesGroupsTableAdapter taDisciplinesGroups = new DisciplinesGroupsTableAdapter();
                        DataTable dt = taDisciplinesGroups.GetData();
                        DataTable dtOutput = UploadHelper.Upload(dt, syncParams);

                        // Update local DB
                        foreach (DataRow dr in dt.Rows)
                        {
                            dr["Sync"] = true;
                            taDisciplinesGroups.Update(dr);
                        }

                        progress += 1;
                        this.bw.ReportProgress(progress);
                    }

                    if (chkDisciplines.Checked)
                    {
                        this.syncParams = new SyncParameters();
                        this.syncParams.ActiveTable = AtletisService.Tables.Disciplines;
                        this.syncParams.ActiveTableSpecified = true;

                        DisciplinesTableAdapter taDisciplines = new DisciplinesTableAdapter();
                        DataTable dt = taDisciplines.GetData();
                        DataTable dtOutput = UploadHelper.Upload(dt, syncParams);

                        // Update local DB
                        foreach (DataRow dr in dt.Rows)
                        {
                            string filter = "[WebId] = " + dr["ID"].ToString();
                            dr["WebId"] = dtOutput.Select(filter)[0]["ID"];
                            dr["Sync"] = true;
                            taDisciplines.Update(dr);
                        }

                        progress += 1;
                        this.bw.ReportProgress(progress);
                    }

                    #endregion

                    #region Countries

                    if (chkCountries.Checked)
                    {
                        this.syncParams = new SyncParameters();
                        this.syncParams.ActiveTable = AtletisService.Tables.Countries;
                        this.syncParams.ActiveTableSpecified = true;

                        CountriesTableAdapter taCountries = new CountriesTableAdapter();
                        DataTable dt = taCountries.GetData();
                        DataTable dtOutput = UploadHelper.Upload(dt, syncParams);

                        // Update local DB
                        foreach (DataRow dr in dt.Rows)
                        {
                            dr["Sync"] = true;
                            taCountries.Update(dr);
                        }

                        progress += 1;
                        this.bw.ReportProgress(progress);
                    }

                    #endregion

                    #region Clubs

                    if (chkClubs.Checked)
                    {
                        this.syncParams = new SyncParameters();
                        this.syncParams.ActiveTable = AtletisService.Tables.ClubsGroups;
                        this.syncParams.ActiveTableSpecified = true;

                        ClubsGroupsTableAdapter taClubsGroups = new ClubsGroupsTableAdapter();
                        DataTable dt = taClubsGroups.GetData();
                        DataTable dtOutput = UploadHelper.Upload(dt, syncParams);

                        // Update local DB
                        foreach (DataRow dr in dt.Rows)
                        {
                            dr["Sync"] = true;
                            taClubsGroups.Update(dr);
                        }

                        progress += 1;
                        this.bw.ReportProgress(progress);
                    }

                    if (chkClubs.Checked)
                    {
                        this.syncParams = new SyncParameters();
                        this.syncParams.ActiveTable = AtletisService.Tables.Clubs;
                        this.syncParams.ActiveTableSpecified = true;

                        ClubsTableAdapter taClubs = new ClubsTableAdapter();
                        DataTable dt = taClubs.GetData();
                        DataTable dtOutput = UploadHelper.Upload(dt, syncParams);

                        // Update local DB
                        foreach (DataRow dr in dt.Rows)
                        {
                            dr["Sync"] = true;
                            taClubs.Update(dr);
                        }

                        progress += 1;
                        this.bw.ReportProgress(progress);
                    }

                    #endregion

                    #region Competitors

                    if (chkCompetitors.Checked)
                    {
                        this.syncParams = new SyncParameters();
                        this.syncParams.ActiveTable = AtletisService.Tables.Competitors;
                        this.syncParams.ActiveTableSpecified = true;

                        CompetitorsTableAdapter taCompetitors = new CompetitorsTableAdapter();
                        DataTable dt = taCompetitors.GetData();
                        DataTable dtOutput = UploadHelper.Upload(dt, syncParams);

                        // Update local DB
                        foreach (DataRow dr in dt.Rows)
                        {
                            string filter = "[WebId] = " + dr["ID"].ToString();
                            dr["WebId"] = dtOutput.Select(filter)[0]["ID"];
                            dr["Sync"] = true;
                            taCompetitors.Update(dr);
                        }

                        progress += 1;
                        this.bw.ReportProgress(progress);
                    }

                    #endregion

                    #region ChipTags

                    if (chkChipTags.Checked)
                    {
                        this.syncParams = new SyncParameters();
                        this.syncParams.ActiveTable = AtletisService.Tables.ChipTagsGroups;
                        this.syncParams.ActiveTableSpecified = true;

                        ChipTagsGroupsTableAdapter taChipTagsGroups = new ChipTagsGroupsTableAdapter();
                        DataTable dt = taChipTagsGroups.GetData();
                        DataTable dtOutput = UploadHelper.Upload(dt, syncParams);

                        // Update local DB
                        foreach (DataRow dr in dt.Rows)
                        {
                            string filter = "[WebId] = " + dr["ID"].ToString();
                            dr["WebId"] = dtOutput.Select(filter)[0]["ID"];
                            dr["Sync"] = true;
                            taChipTagsGroups.Update(dr);
                        }

                        progress += 1;
                        this.bw.ReportProgress(progress);
                    }

                    if (chkChipTags.Checked)
                    {
                        this.syncParams = new SyncParameters();
                        this.syncParams.ActiveTable = AtletisService.Tables.ChipTags;
                        this.syncParams.ActiveTableSpecified = true;

                        ChipTagsTableAdapter taChipTags = new ChipTagsTableAdapter();
                        DataTable dt = taChipTags.GetData();
                        DataTable dtOutput = UploadHelper.Upload(dt, syncParams);

                        // Update local DB
                        foreach (DataRow dr in dt.Rows)
                        {
                            dr["Sync"] = true;
                            taChipTags.Update(dr);
                        }

                        progress += 1;
                        this.bw.ReportProgress(progress);
                    }

                    #endregion
                }

                if (this.bUploadPreChipData)
                {
                    #region PreChipData

                    DataTable dt = DatabaseHelper.GetPreChipDataByCompetitionId(Globals.ActiveCompetition.ID);

                    if (dt != null && dt.Rows.Count > 0)
                    {
                        int count = UploadHelper.UploadPreChipData(dt);
                    }

                    progress += 1;
                    this.bw.ReportProgress(progress);

                    #endregion
                }

                Thread.Sleep(5000);
            }
            catch (FaultException ex)
            {
                MessageBox.Show("Nastala chyba vo WS:" + Environment.NewLine + ex.Message, 
                    "Upload", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            catch (Exception ex)
            {
                MessageBox.Show("Nastala chyba v aplikácii:" + Environment.NewLine + ex.Message, 
                    "Upload", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        
        void backgroundWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            
        }

        void backgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            if (this.bContinueSync)
            {
                this.lblProgress.Text = string.Format("{0} upload ukončený, trvanie: {1}ms", 
                    DateTime.Now.ToString("HH:mm:ss"), 
                    (int)(DateTime.Now - this.dtStart).TotalMilliseconds);

                // Ak uploadujem preteky, tak pokracujem dalsim uploadom
                if (this.bUploadCompetitionData)
                    this.bw.RunWorkerAsync();
                else
                    this.lblProgress.Text += ", upload OFF!";
            }
            else
            {
                this.lblProgress.Text = "Upload OFF!";
            }
        }

        #endregion
    
    }
}
